package cn.com.zsc.util;

import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.security.MessageDigest;
import java.util.Hashtable;
import java.util.Vector;

import net.sf.json.JSONArray;

import com.jarp.db.DAO;

public class StringUtils {

	/**
	 * 根据传入的字符串和分隔符将字符串分割为字符串数组
	 * 
	 * @param string
	 * @param split
	 * @return
	 */
	public static String[] split(String str, char separatorChar) {
		String[] result = org.apache.commons.lang.StringUtils.split(str,
				separatorChar);
		return result;
	}

	/**
	 * 根据传入的字符串和分隔字符串将字符串分割为字符串数组
	 * 
	 * @param str
	 * @param separatorChars
	 * @return
	 */
	public static String[] split(String str, String separatorChars) {
		String[] result = org.apache.commons.lang.StringUtils.split(str,
				separatorChars);
		return result;
	}

	/**
	 * 全部替换字符串中指定的字符串
	 * 
	 * @param str
	 * @param searchChars
	 * @param replaceChars
	 * @return
	 */
	public static String replaceAll(String str, String searchChars,
			String replaceChars) {
		String result = org.apache.commons.lang.StringUtils.replace(str,
				searchChars, replaceChars);
		return result;
	}

	public static final String BLANK = "";

	/**
	 * 输入两个字符�?,将类型转化后返回差�??
	 * 
	 * @param a
	 * @param b
	 * @return
	 */
	public static String getChaE(String a, String b) {
		a = StringUtils.nil(a, "0");
		b = StringUtils.nil(b, "0");
		BigDecimal bd = new BigDecimal(Double.parseDouble(a)
				- Double.parseDouble(b));
		double tempValue = bd.setScale(4, BigDecimal.ROUND_HALF_UP).doubleValue();
		return StringUtils.nil((tempValue) + "", "0");
	}

	/**
	 * 输入两个字符�?,将类型转化后返回比�??
	 * 
	 * @param a
	 * @param b
	 * @return
	 */
	public static double getRate(String a, String b) {
		a = StringUtils.nil(a, "0");
		b = StringUtils.nil(b, "1");
		if (Double.parseDouble(b) == 0) {
			b = "1";
		}
		BigDecimal bd = new BigDecimal(Double.parseDouble(a)
				/ Double.parseDouble(b) * 100);
		double tempValue = bd.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
		return tempValue;
	}

	/**
	 * �?查字符串对象是否为空 当字符串为NULL，返回TRUE 当字符串长度为零，返回TRUE�?
	 * 
	 * @param str
	 * @return boolean
	 */
	public static boolean nil(String str) {
		// NULLTrue
		if (null == str) {
			return true;
		}
		// True
		if (0 == str.length()) {
			return true;
		}
		// False
		return false;
	}

	/**
	 * 字符串检查，当字符串为NULL时，返回�?个空字符�?
	 * 
	 * @param sIn
	 * @return String
	 */
	public static String nvl(String sIn) {
		// NULL""
		return nvl(sIn, StringUtils.BLANK);
	}

	/**
	 * 字符串检查，当字符串为NULL时，返回�?个自定义的字�?
	 * 
	 * @param sIn
	 * @param sDef：自定义的字�?
	 * @return String
	 */
	public static String nvl(String sIn, String sDef) {
		// NULL
		if (null == sIn) {
			return sDef;
		} else if (0 == sIn.length()) {
			return sDef;
		} else {
			return sIn;
		}
	}

	/**
	 * 如果第一个字符串不为空则返回该字符串,否则返回第二�?
	 */
	public static String nil(String s, String _default) {
		if (nil(s))
			return _default;
		else
			return s;
	}

	/**
	 * 判断字符串数组是否为�?
	 */
	public static boolean nil(String[] s) {
		return (s == null || s.length == 0);
	}

	/**
	 * 如果数组为空,则返回空数组
	 */
	public static String[] notNil(String[] s) {
		if (s == null || s.length == 0) {
			return new String[0];
		}
		return s;
	}

	/**
	 * 改变字符串编码到gbk
	 */
	public static String toGBK(String src) {
		if (nil(src))
			return "";
		String s = null;
		try {
			s = new String(src.getBytes("ISO-8859-1"), "gb2312");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return s;
	}

	/**
	 * 改变字符串编码到utf8 2009-03-17 修改 xuyan
	 */
	public static String toUTF8(String src) {
		if (nil(src))
			return "";
		String s = null;
		try {
			byte[] bSrc = src.getBytes("UTF-8"); // here should not be
													// "ISO-8859-1"
			// cause you have multibytes character in your string
			byte[] bBomSrc = new byte[bSrc.length + 3];
			bBomSrc[0] = (byte) 0xEF; // add bom infomation; EF BB BF
			bBomSrc[1] = (byte) 0xBB;
			bBomSrc[2] = (byte) 0xBF;
			System.arraycopy(bSrc, 0, bBomSrc, 3, bSrc.length);
			s = new String(bBomSrc, "UTF-8"); // right way
			// s = new String(bSrc,"UTF-8"); // wrong way with no bom
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return s;
	}

	/**
	 * 替换字符串
	 * @param line
	 * @param oldString
	 * @param newString
	 * @return
	 */
	public static String replace(String line, String oldString, String newString) {
		if (line == null) {
			return null;
		}
		int i = 0;
		if ((i = line.indexOf(oldString, i)) >= 0) {
			char[] line2 = line.toCharArray();
			char[] newString2 = newString.toCharArray();
			int oLength = oldString.length();
			StringBuffer buf = new StringBuffer(line2.length);
			buf.append(line2, 0, i).append(newString2);
			i += oLength;
			int j = i;
			while ((i = line.indexOf(oldString, i)) > 0) {
				buf.append(line2, j, i - j).append(newString2);
				i += oLength;
				j = i;
			}
			buf.append(line2, j, line2.length - j);
			return buf.toString();
		}
		return line;
	}

	/**
	 * UNICODE to 中文
	 * 该函数要求输入的字符全部是unicode格式的
	 */
	public static String toChinese(String thisStr) {
		if (thisStr == null || thisStr.equals("") || thisStr.length() % 6 != 0
				|| !thisStr.startsWith("\\u"))
			return thisStr;
		int start = 0;
		int end = 0;
		StringBuffer sb = new StringBuffer();
		while (start > -1) {
			end = thisStr.indexOf("\\u", start + 2);
			String charStr = "";
			if (end == -1) {
				charStr = thisStr.substring(start + 2, thisStr.length());
			} else {
				charStr = thisStr.substring(start + 2, end);
			}
			char letter = (char) Integer.parseInt(charStr, 16);
			sb.append(new Character(letter).toString());
			start = end;
		}
		return sb.toString();
	}

	/**
	 * UNICODE to 中文
	 * 该函数允许unicode与一般字符混合型的字符串
	 */
	public static String toChinese2(String thisStr) {
		if (thisStr == null || thisStr.equals(""))
			return thisStr;

		StringBuffer sb = new StringBuffer();

		int uPos = -1;
		int start = 0;
		while ((uPos = thisStr.indexOf("\\u", start)) > -1) {
			String charStr = thisStr.substring(uPos + 2, uPos + 6);

			sb.append(thisStr.substring(start, uPos));

			char letter = (char) Integer.parseInt(charStr, 16);
			start = uPos + 6;
			sb.append(new Character(letter).toString());
		}
		sb.append(thisStr.substring(start));
		return sb.toString();
	}

	/**
	 * 中文 to UNICODE
	 */
	public static String toUnicode(String thisStr) {
		if (thisStr == null || thisStr.equals(""))
			return "";
		char[] arrChar = thisStr.toCharArray();
		String rtnStr = "";
		for (int i = 0; i < arrChar.length; i++) {
			int iVal = (int) thisStr.charAt(i);
			if (iVal <= 256) {
				rtnStr += "\\u00" + Integer.toHexString(iVal);
			} else {
				rtnStr += "\\u" + Integer.toHexString(iVal);
			}
		}
		return rtnStr;
	}

	/**
	 * left trim
	 */
	public static String ltrim(String input, char trimthis) {
		if (input.indexOf(trimthis) == 0) {
			input = input.substring(1);
			input = ltrim(input, trimthis);
		}
		return input;
	}

	/**
	 * right trim
	 */
	public static String rtrim(String input, char trimthis) {
		int len = input.length();
		if (len > 0 && input.charAt(len - 1) == trimthis) {
			input = input.substring(0, len - 1);
			input = rtrim(input, trimthis);
		}
		return input;
	}

	/**
	 * trim left and right
	 */
	public static String trim(String input, char trimthis) {
		return ltrim(rtrim(input, trimthis), trimthis);
	}

	/**
	 * 将密码进行加密
	 * @param password
	 * @param algorithm
	 * @return
	 */
	public static String encodePassword(String password, String algorithm) {
		byte[] unencodedPassword = password.getBytes();

		MessageDigest md = null;

		try {
			md = MessageDigest.getInstance(algorithm);
		} catch (Exception e) {
			return password;
		}

		md.reset();

		md.update(unencodedPassword);

		// 计算hash
		byte[] encodedPassword = md.digest();

		StringBuffer buf = new StringBuffer();

		for (int i = 0; i < encodedPassword.length; i++) {
			if ((encodedPassword[i] & 0xff) < 0x10) {
				buf.append("0");
			}

			buf.append(Long.toString(encodedPassword[i] & 0xff, 16));
		}

		return buf.toString();
	}
	
	/**
	 * 根据数据字典ID获取数据字典
	 * @param plCode
	 * @return
	 */
	@SuppressWarnings("unchecked")
	public String getComboBox(String plCode) {
		String sql = "select CL_CODE, CL_NAME from cm_commlist where PL_Code=" + plCode + " order by IDX";

		DAO dao = new DAO();
		Vector<Hashtable<String, String>> v = new Vector<Hashtable<String, String>>();

		String resultStr = "";

		try {
			v = dao.getDataSet(ConstValue.DBNAME, sql);

			if (v != null) {
				JSONArray json = new JSONArray();
				json = JSONArray.fromObject(v);
				resultStr = json.toString();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		return resultStr;
	}
	
	/**
	 * 判断是否是中文字符
	 * @param c
	 * @return
	 */
	public static boolean isChinese(char c) {
		Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
		if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
				|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
				|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
				|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
				|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
			return true;
		}
		return false;
	}

	/**
	 * 判断是否是中文
	 * @param strName
	 */
	public static boolean isChinese(String strName) {
		char[] ch = strName.toCharArray();
		
		boolean flag = false;
		
		for (int i = 0; i < ch.length; i++) {
			char c = ch[i];
			
			flag = isChinese(c);
		}
		
		return flag;
	}
}
